var util = require("util");

var JSONUtil = function () {
    this.buffers = [];
};

JSONUtil.prototype.concat = function (buffer) {
    this.buffers.push(buffer);
    return this;
};

JSONUtil.prototype.empty = function () {
    this.buffers = [];
    return this;
};

JSONUtil.prototype.toBuffer = function () {
    return Buffer.concat(this.buffers);
};

JSONUtil.prototype.toString = function (encoding) {
    return this.toBuffer().toString(encoding);
};

JSONUtil.prototype.load = function (stream, callback) {
    var that = this;
    stream.on('data', function (trunk) {
        that.concat(trunk);
    });
    stream.on('end', function () {
        callback(null, that.toBuffer());
    });
    stream.once('error', callback);
};
JSONUtil.prototype.parseRequest = function (stream, callback) {
    var that = this;
    stream.on('data', function (trunk) {
        that.concat(trunk);
    });
    stream.on('end', function () {
        var body;
        try {
            body = JSON.parse(that.toBuffer().toString());
        }
        catch (e) {
            callback("body parse error");
        }
        if (!body || !util.isArray(body)) {
            callback("body parse error");
        } else {
            callback(null, body);
        }
    });
    stream.once('error', callback);
}
JSONUtil.prototype.parseResponse = function (stream, callback) {
    var that = this;
    stream.on('data', function (trunk) {
        that.concat(trunk);
    });
    stream.on('end', function () {
        var error;
        var data;
        try {
            data = JSON.parse(that.toBuffer().toString());
        }
        catch (e) {
            error = e.message;
        }
        if (error) {
            callback(error);
        } else {
            callback(null, data);
        }
    });
    stream.once('error', callback);
}
module.exports = JSONUtil;
